import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:ws_group_chat/pages/client/client_chat_page.dart';
import 'package:ws_group_chat/provider/client_data.dart';

class ClientWaitPage extends StatefulWidget {
  const ClientWaitPage({super.key});

  @override
  State<ClientWaitPage> createState() => _ClientWaitPageState();
}

class _ClientWaitPageState extends State<ClientWaitPage> {
  late final ClientData _clientData;
  bool _isToChatPage = false;

  @override
  void initState() {
    super.initState();
    _clientData = context.read<ClientData>();
    _clientData.onChatRoomStarted = _onChatRoomStarted;
  }

  bool _onChatRoomStarted() {
    setState(() {
      _isToChatPage = true;
    });
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => const ClientChatPage()),
    );
    return true;
  }

  @override
  void dispose() {
    if (!_isToChatPage) {
      _clientData.close();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('等待玩家'),
        backgroundColor: Colors.transparent,
      ),
      body: Consumer<ClientData>(
        // 这里不使用 Selector 原因是appData的数据量不多，所以没必要使用Selector
        builder: (context, vm, child) {
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('${vm.playersCount}人已加入'),
                const SizedBox(height: 40, width: double.infinity),
                const Text('请分享二维码给其他玩家'),
                QrImageView(
                  data: vm.wsUrl!,
                  version: QrVersions.auto,
                  size: 200.0,
                ),
                const SizedBox(height: 16),
                Text(vm.wsUrl!, style: Theme.of(context).textTheme.bodyMedium),
                const Spacer(),
              ],
            ),
          );
        },
      ),
    );
  }
}
